﻿using Fun.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fun.FontDecode
{
    /// <summary>
    /// 静态字体解密程序，适用于动态生成的字体里Unicode字符编码与原文始终固定的情况。
    /// 原理：得到加密字符对应的Unicode编码，再将编码与已解密的数据比对，得到原始字符。
    /// </summary>
    public class StaticFontDecoder : IFontDecoder
    {
        IDictionary<string, string> FTextMappings;

        /// <summary>
        /// 构造。
        /// </summary>
        /// <param name="textMapping">Unicode编码与解密字符映射表，XXXX=解密字符，由工具解析生成</param>
        public StaticFontDecoder(IDictionary<string, string> textMapping)
        {
            FTextMappings = textMapping;
        }
        
        public string Decode(string s)
        {
            var chars = StringHelper.ExtractTextAll(s, "&#x", ";")
                .Distinct()
                .ToArray();
            var decodes = chars
                .Where(x => FTextMappings.ContainsKey(x))
                .Select(x => FTextMappings[x])
                .ToArray();
            
            if (decodes.Length != chars.Length)
                return "解码失败。";

            var result = s;
            for (var i = 0; i < chars.Length; i++)
                result = result.Replace($"&#x{chars[i]};", decodes[i]);
            return result;
        }
    }
}
